package com.cc.Servlet;

import com.alibaba.fastjson.JSON;
import com.cc.Service.EmployeeService;
import com.cc.Service.Impl.EmployeeServiceImpl;
import com.cc.eneity.Employee;
import util.FileUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.List;

@WebServlet("/employee.do")
@MultipartConfig//提供文件上传功能
public class EmployeeServlet extends HttpServlet {
    private EmployeeService employeeService = new EmployeeServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数 判断List add update delete
        String method = req.getParameter("method") == null ? "" : req.getParameter("method");
        switch (method) {
            case "list":
                list(req, resp);
                break;
            case "add":
                add(req, resp);
                break;

        }
    }

    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //员工姓名
        String empName = req.getParameter("empName");
        List<Employee> employeeList = employeeService.getAll(empName);
        //将数据转成json
        String json = JSON.toJSONString(employeeList);
        resp.getWriter().write(json);
    }

    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端参数
        String empName = req.getParameter("empName");
        String depId = req.getParameter("depId");
        String position = req.getParameter("position");
        String startDate = req.getParameter("startDate");
        String phone = req.getParameter("phone");
        String birthday = req.getParameter("birthday");
        //接收文件
        Part part = req.getPart("imgUrl");
        String path = FileUtil.uploadFile(req, part);
        Employee employee = new Employee();
        employee.setEmpName(empName);
        employee.setDepId(depId);
        employee.setPosition(position);
        employee.setStartDate(startDate);
        employee.setPhone(phone);
        employee.setBirthday(birthday);
        employee.setStart("1");
        //设置员工状态
        employee.setStart("0");
        boolean result = employeeService.add(employee);
        if (result) {
            //跳转到List页面
            resp.sendRedirect("emp.jsp");
        }
    }
}
